<!--
 * @description: 编辑组境
 * @fileName: EditLens
 * @author: 17076
 * @date: 2025/2/20-下午4:02
 * @version: V1.0.0
-->

<template>
  <cs-dialog
    :dialog="dialogOption"
    @onSubmit="save"
  >
    <div slot="content">
      <el-form ref="form" :model="infoForm" :rules="rules" label-width="100px">
        <el-row :gutter="10">
          <!--          <el-col v-if="isEdit" :span="8">-->
          <!--            <el-form-item label="编号" prop="lensNo">-->
          <!--              <span>{{ infoForm['lensNo'] }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="组镜头标题" prop="lensName">
              <el-input v-model="infoForm['lensName']" placeholder="组镜头标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时间" prop="lensTime">
              <el-select v-model="infoForm['lensTime']" placeholder="请选择时间">
                <el-option
                  v-for="item in timeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="景别" prop="shotSize">
              <el-select v-model="infoForm['shotSize']" placeholder="请选择景别">
                <el-option
                  v-for="item in sceneTypeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="场景" prop="scenery">
              <el-input v-model="infoForm['scenery']" type="textarea" :rows="3" clearable show-word-limit maxlength="100" placeholder="请输入场景" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="剧情" prop="plot">
              <el-input v-model="infoForm['plot']" type="textarea" :rows="3" placeholder="请输入剧情" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色" prop="dialogues">
              <vxe-grid ref="xTable" v-bind="gridOption">
                <template #edit_roles="{ row }">
                  <el-select v-model="row['playRoleId']" clearable placeholder="请选择角色">
                    <el-option
                      v-for="item in roleList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                      :disabled="formatterRoleStatus(item.id)"
                    />
                  </el-select>
                </template>
                <template #edit_description="{ row }">
                  <el-select v-model="row['narrativeType']" clearable placeholder="请选择叙事方式">
                    <el-option
                      v-for="item in narrativeTypeList"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </template>
                <template #edit_content="{ row }">
                  <el-input v-model="row['dialogueInfo']" clearable placeholder="请输入对话内容" />
                </template>
                <template #roles="{ row }">
                  <span class="title">{{ formatterRoleLabel(row.playRoleId) }}</span>
                </template>
                <template #description="{ row }">
                  <span class="title">{{ formatterDescriptionLabel(row.narrativeType) }}</span>
                </template>
                <template #content="{ row }">
                  <span class="title">{{ row['dialogueInfo'] }}</span>
                </template>
                <template #opera="{ row, rowIndex }">
                  <i class="el-icon-delete" style="cursor: pointer;color: white" @click="handleDelete(row, rowIndex)" />
                </template>
              </vxe-grid>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <p style="text-align: center">
              <el-button icon="el-icon-circle-plus-outline" @click="handleAddRoles">添加角色</el-button>
            </p>
          </el-col>
          <el-col :span="24">
            <el-form-item label="旁白" prop="voiceover">
              <el-input v-model="infoForm['voiceover']" placeholder="请输入旁白" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </cs-dialog>
</template>

<script>
import mixin from '@/views/mixin'
import { saveLens } from '@/api/play'
import { selectPlayRole } from '@/api/roles'
import { mapActions } from 'vuex'
export default {
  name: 'EditLens',
  props: {
    playId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogOption: {
        top: '5%',
        width: '55%',
        title: {
          title: '编辑组镜'
        },
        show: false
      },
      // 场景列表
      sceneList: [
        { name: '宫殿朝堂', code: '1' },
        { name: '沙漠', code: '2' },
        { name: '豪门宫邸', code: '3' }
      ],
      infoForm: {},
      rules: {
        // lensName: [{ required: true, trigger: 'blur', message: '镜头标题不能为空!' }],
        plot: [{ required: true, trigger: 'blur', message: '剧情不能为空!' }],
        scenery: [{ required: true, trigger: 'blur', message: '场景不能为空!' }]
      },
      // 角色列表
      roleList: [],
      // 叙事方式
      narrativeTypeList: JSON.parse(sessionStorage.getItem('narrativeType')),
      gridOption: {
        ...mixin.data().gridOptions,
        height: 270,
        editConfig: {
          trigger: 'click',
          mode: 'row'
        },
        columns: [
          { field: 'playRoleId', title: '角色', width: 150, align: 'center', slots: { edit: 'edit_roles', default: 'roles' }, editRender: {}},
          { field: 'narrativeType', title: '叙事方式', width: 150, align: 'center', slots: { edit: 'edit_description', default: 'description' }, editRender: {}},
          { field: 'dialogueInfo', title: '对话内容', align: 'center', slots: { edit: 'edit_content', default: 'content' }, editRender: {}},
          { title: '操作', width: 80, align: 'center', slots: { default: 'opera' }}
        ],
        data: []
      },
      timeList: JSON.parse(sessionStorage.getItem('lensTime')),
      sceneTypeList: JSON.parse(sessionStorage.getItem('shotSize')),
      // 是否是编辑
      isEdit: false
    }
  },
  methods: {
    ...mapActions({
      setSelectLens: 'lens/setSelectLens'
    }),
    // 显示弹窗
    show(data, isEdit) {
      if (isEdit) {
        this.infoForm = this.$baseLodash.cloneDeep(data)
        // 对话数据
        this.gridOption.data = (data['dialogues'] && data['dialogues'].length > 0) ? this.$baseLodash.cloneDeep(data['dialogues']) : []
      } else {
        this.infoForm = {}
        this.$set(this.infoForm, 'partId', data['partId'])
        this.$set(this.infoForm, 'lensNo', data['lensNo'])
        this.$set(this.infoForm, 'dialogues', data['dialogues'])
        this.gridOption.data = []
        // this.$set(this.infoForm, 'roles', data['roles'])
      }
      this.isEdit = isEdit
      this.dialogOption.title.title = isEdit ? '编辑组镜' : '添加组镜'
      this.dialogOption.show = true
      this.fetchRoles()
    },
    // 格式化角色可选状态
    formatterRoleStatus(val) {
      // 如何表格数据中存在该角色，则不可选
      return this.gridOption.data.some(item => item['playRoleId'] === val)
    },
    // 格式化角色label 显示
    formatterRoleLabel(code) {
      if (!code) return ''
      const item = this.roleList.find(item => item['id'] === code)
      return item ? item.name : ''
    },
    // 格式化叙事方式label 显示
    formatterDescriptionLabel(code) {
      if (!code) return ''
      const item = this.narrativeTypeList.find(item => item.code === code)
      return item ? item.name : ''
    },
    // 查询角色列表
    fetchRoles() {
      selectPlayRole({ playId: this.playId }).then(res => {
        this.roleList = res.data.result
      })
    },
    // 删除？
    handleDelete(row, rowIndex) {
      this.gridOption.data.splice(rowIndex, 1)
    },
    // 添加角色
    handleAddRoles() {
      this.gridOption.data.push({})
    },
    save(callback) {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          // 保存时判断是否含有对话
          if (this.gridOption.data.length > 0) {
            const data = this.$refs.xTable.getFullData()
            this.$set(this.infoForm, 'dialogues', data)
          }
          const { code, msg } = await saveLens(this.infoForm)
          code === 200 ? this.$baseMessage.success(msg || this.isEdit ? '编辑成功' : '新建成功') : this.$baseMessage.error(msg || '新建失败')
          // 清空选中的分镜
          await this.setSelectLens(null)
          this.$emit('reloadData')
          callback(true)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep {
  .el-select {
    width: 100%;
  }
  .title {
    color: #FFFFFF;
  }
}
</style>
